import store from "../../utils/store";
import {
    getDay
} from '../../utils/date'
import dayjs from "dayjs";
import router from "../../utils/router";
const app = getApp();
Page({
    data: {
        allCars: 0,
        dataSource: [],
        pageNum: 0,
        pageSize: 15,
        dataMore: true,
        totalCount: 0, // 累计装载量
        todayCount: 0, // 当日装载量（已完成的）
        title: '订单数据',
        today: false,
        minDate: new Date(2020, 0, 1).getTime(),
        maxDate: new Date().getTime(),
        show: false,
        startTime: getDay(-7),
        endTime: getDay(0),
    },
    async onLoad(options) {
        if (options && options.today === 'today') {
            this.setData({
                today: true,
                startTime: dayjs().format('YYYY-MM-DD'),
                endTime: dayjs().format('YYYY-MM-DD')
            })
            await this.getTodayLoadingCount()
            await this.getAllCarsByToday()
            await this.getOrderList()
        } else {
            this.setData({
                today: false,
                startTime: getDay(-180),
                endTime: dayjs().format('YYYY-MM-DD')
            })
            await this.getLoadingDataByTotal()
            await this.getAllCars()
            await this.getOrderList()
        }
    },
    // 点击时间区间事件
    handleClickTime() {
        this.setData({
            show: true
        })
    },
    onClose() {
        this.setData({
            show: false
        })
    },
    onConfirm(event) {
        let [start, end] = event.detail;
        start = dayjs(start).format('YYYY-MM-DD')
        end = dayjs(end).format('YYYY-MM-DD')
        this.setData({
            startTime: start,
            endTime: end,
            show: false
        })
    },
    handleSearch() {
        this.setData({
            dataSource: [],
            dataMore: true,
            pageNum: 0,
            pageSize: 10
        })
        this.getOrderList()
        this.getAllCars()
        this.getLoadingDataByTotal()
    },
    // 点击导出按钮
    async handleClickExport() {
        wx.showLoading({
            title: '正在导出数据',
        })
        const that = this
        console.log('点击了导出按钮')
        const factoryId = store.getItem("factoryId")
        wx.request({
            url: `https://mingduzscloud.com/api/v3/task/queryList/factoryId/${factoryId}`,
            data: {
                startTime: this.data.startTime + " 00:00:00",
                endTime: this.data.endTime + " 23:59:59"
            },
            method: 'POST',
            header: {
                'content-type': 'application/json', // 默认值
                'Authorization': 'driver',
                'phoneNumber': store.getItem("phoneNumber")
            },
            success(res) {
                console.log('导出的res', res)
                if (res.data && res.data.message === "Export xls Failed") {
                    wx.showToast({
                        title: '导出失败请检查',
                        icon: 'error',
                        duration: 2000
                    })
                    return
                } else {
                    that.downloadExcel(res.data.data)
                }
            },
            fail(error) {
                console.log(error)
                wx.showToast({
                    title: '导出失败请检查',
                    icon: 'error',
                    duration: 2000
                })
            }
        })
    },
    downloadExcel(url) {

        const currentCompany = store.getItem("selectCompany")
        wx.downloadFile({
            url: `https://mingduzscloud.com/api/app/getTaskXls/xx.xls?name=${url}`, //仅为示例，并非真实的资源
            success(res) {
                const manage = wx.getFileSystemManager();
                const today = dayjs().unix() // 1548381600
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                    manage.saveFile({
                        tempFilePath: res.tempFilePath,
                        filePath: `${wx.env.USER_DATA_PATH}/${currentCompany.name}${today}订单数据.xlsx`, // 文件重命名 可自定义
                        success: function (res) {
                            wx.hideLoading()
                            wx.openDocument({
                                filePath: res.savedFilePath,
                                showMenu: true,
                                success: function (res) {
                                    console.log('打开文档成功')
                                }
                            })
                        },
                        fail: function () {
                            wx.showToast({
                                title: '导出数据失败',
                                icon: 'error',
                                duration: 2000
                            })
                            wx.hideLoading()
                        }
                    });

                }
            }
        })
    },
    // 获取当日装量
    async getTodayLoadingCount() {
        const factoryId = store.getItem("factoryId")
        try {
            const res = await app.clientPost(`${app.ClientApi.getTodayLoadedData}/factoryId/${factoryId}`, {
                startTime: dayjs().format('YYYY-MM-DD') + " 00:00:00",
                endTime: dayjs().format('YYYY-MM-DD') + " 23:59:59"
            }, {
                loading: false
            })
            // 获取40kg规格的数量 每一项都是装了多少包
            // const fourthNumArr = res.map(item => {
            //     if (item.materialName ==='40kg') {
            //         if (item.supplementNumber === undefined || item.supplementNumber === null) {
            //             item.supplementNumber = 0
            //         }
            //         return item.coordinateId + item.supplementNumber
            //     }
            // })
            // 获取50kg规格的数组 每一项都是装了多少包
            // const fivethNumArr = res.map(item => {
            //     if (!item.materialName || item.materialName && item.materialName !== '40kg') {
            //         if (item.supplementNumber === undefined || item.supplementNumber === null) {
            //             item.supplementNumber = 0
            //         }
            //         return item.coordinateId + item.supplementNumber
            //     }
            // })
            // 如果为空的话默认设为0
            // const fourthData = fourthNumArr.map(item => {
            //     if (item === undefined) {
            //         item = 0
            //     }
            //     return item
            // })
             // 如果为空的话默认设为0
            // const fivethData = fivethNumArr.map(item => {
            //     if (item === undefined) {
            //         item = 0
            //     }
            //     return item
            // })
            // const fourthNum = fourthData.reduce((total, current) => {
            //     return total + current
            // }, 0)
            // const fivethNum = fivethData.reduce((total, current) => {
            //     return total + current
            // }, 0)
            // const sums = res.map(item => {
            //     if (item.supplementNumber === undefined) {
            //         item.supplementNumber = 0
            //     }
            //     return item.coordinateId + item.supplementNumber
            // })
            // const totalCount = fourthNum ? (fourthNum * 0.04 + fivethNum * 0.05).toFixed(2) : (fivethNum * 0.05).toFixed(2)
            // const totalCount = sums.reduce((total, item) => {
            //     return total + item
            // }, 0) / 20
            this.setData({
                todayCount: res
            })
        } catch (e) {
            this.setData({
                totalCount: '暂无数据'
            })
        }

    },

    // 获取今天的车辆数据
    async getAllCarsByToday() {
        const startTime = dayjs().format('YYYY-MM-DD')
        const endTime = dayjs().format('YYYY-MM-DD')
        const factoryId = store.getItem("factoryId")
        const res = await app.clientPost(`${app.ClientApi.getAllCarList}/page-num/1/page-size/10/factoryId/${factoryId}`, {
            startTime: startTime + " 00:00:00",
            endTime: dayjs().format('YYYY-MM-DD') + " 23:59:59"
        })
        this.setData({
            allCars: res.total
        })
    },

    // 根据时间来获取车辆数量
    async getAllCars() {
        const startTime = this.data.startTime + " 00:00:00"
        const endTime = this.data.endTime + " 23:59:59"
        const factoryId = store.getItem("factoryId")
        const res = await app.clientPost(`${app.ClientApi.getAllCarList}/page-num/1/page-size/10/factoryId/${factoryId}`, {
            startTime,
            endTime
        })
        this.setData({
            allCars: res.total
        })
    },

    // 点击跳转到车辆列表页面
    toCarListByTotal() {
        router.push('carlist')
    },

    // 获取累计水泥吨数
    async getLoadingDataByTotal() {
        const startTime = this.data.startTime
        const endTime = this.data.endTime
        const factoryId = store.getItem("factoryId")
        try {
            const res = await app.clientGet(`${app.ClientApi.getLoadingData}/${startTime}/${endTime}/factoryId/${factoryId}`)
             // 获取40kg规格的数量 每一项都是装了多少包
             const fourthNumArr = res.map(item => {
                if (item.materialName ==='40kg') {
                    if (item.supplementNumber === undefined || item.supplementNumber === null) {
                        item.supplementNumber = 0
                    }
                    return item.coordinateId + item.supplementNumber
                }
            })
            // 获取50kg规格的数组 每一项都是装了多少包
            const fivethNumArr = res.map(item => {
                if (!item.materialName || item.materialName && item.materialName !== '40kg') {
                    if (item.supplementNumber === undefined || item.supplementNumber === null) {
                        item.supplementNumber = 0
                    }
                    return item.coordinateId + item.supplementNumber
                }
            })
            // 如果为空的话默认设为0
            const fourthData = fourthNumArr.map(item => {
                if (item === undefined) {
                    item = 0
                }
                return item
            })
             // 如果为空的话默认设为0
            const fivethData = fivethNumArr.map(item => {
                if (item === undefined) {
                    item = 0
                }
                return item
            })
            const fourthNum = fourthData.reduce((total, current) => {
                return total + current
            }, 0)
            const fivethNum = fivethData.reduce((total, current) => {
                return total + current
            }, 0)
            const totalCount = fourthNum ? (fourthNum * 0.04 + fivethNum * 0.05).toFixed(2) : (fivethNum * 0.05).toFixed(2)
            this.setData({
                totalCount: totalCount
            })
        } catch (e) {
            this.setData({
                totalCount: '暂无数据'
            })
        }

    },

    async getOrderList() {
        if (!this.data.dataMore) return
        this.data.pageNum++
        const factoryId = store.getItem("factoryId")
        const res = await app.clientPost(`${app.ClientApi.getTodayCarNum}/page-num/${this.data.pageNum}/page-size/${this.data.pageSize}/factoryId/${factoryId}`, {
            startTime: this.data.today ? getDay(0) + " 00:00:00" : this.data.startTime + ' 00:00:00',
            endTime: this.data.today ? getDay(0) + " 23:59:59" : this.data.endTime + ' 23:59:59'
        })
        const newList = [...this.data.dataSource, ...res.list]
        const total = res.total
        this.setData({
            dataSource: newList,
            dataMore: newList.length < total
        })
    },
    async onReachBottom() {
        await this.getOrderList()
    }
});